﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace FaWorks.WebSite.Controllers.Model
{
    public class KnowledgeDetailController : Controller
    {
        #region CRUD
        [HttpGet, ActionName("CURD")]
        public ActionResult HttpGet(int? id)
        {
            return this.Read(id);
        }
        [ValidateInput(false)]
        [HttpPost, ActionName("CURD")]
        public ActionResult HttpPost(Models.Knowledge.KnowledgeDetail knowledgeDetail)
        {
            return this.Create(knowledgeDetail);
        }
        [ValidateInput(false)]
        [HttpPut, ActionName("CURD")]
        public ActionResult HttpPut(Int32 id, Models.Knowledge.KnowledgeDetail knowledgeDetail)
        {
            return this.Update(id, knowledgeDetail);
        }
        [HttpDelete, ActionName("CURD")]
        public ActionResult HttpDelete(Int32 id)
        {
            return this.Delete(id);
        }
        #endregion

        public ActionResult Read(int? id)
        {
            if (id != null) {
                return Json(KlDB.KnowledgeDetails.Find(id), JsonRequestBehavior.AllowGet);
            }

            string detailType = this.HttpContext.Request.QueryString["detailType"];
            if (!String.IsNullOrEmpty(detailType)) {
                StringBuilder sbSql = new StringBuilder();
                sbSql.AppendLine("SELECT m.ID, m.Title, m.Remarks, m.Cases, m.krDisposeType_ID AS DisposeType_ID");
                sbSql.AppendLine("FROM krKnowledgeDetails m");
                sbSql.AppendLine("	INNER JOIN krDetails2Type tab ON m.id = tab.krKnowledgeDetails_ID");
                sbSql.AppendFormat("WHERE tab.krKnowledgeDetailsType_ID = {0}", detailType);

                var models = KlDB.KnowledgeDetails.SqlQuery(sbSql.ToString());
                return Json(models, JsonRequestBehavior.AllowGet);
            }
            detailType = this.HttpContext.Request.QueryString["userDetailType"];
            if (!String.IsNullOrEmpty(detailType))
            {
                StringBuilder sbSql = new StringBuilder();
                sbSql.AppendLine("SELECT m.ID, m.Title, m.Remarks, m.Cases, dt.DisposeType AS DisposeType_Name");
                sbSql.AppendLine("FROM krKnowledgeDetails m");
                sbSql.AppendLine("	LEFT JOIN krDisposeType dt ON m.krDisposeType_ID = dt.ID");
                sbSql.AppendLine("	INNER JOIN krDetails2UserType tab ON m.id = tab.krKnowledgeDetails_ID");
                sbSql.AppendFormat("WHERE tab.krUserKnowledgeDetailsType_ID = {0}", detailType);

                DataTable dt = new DataTable();
                using (SqlConnection sqlConn = new SqlConnection(KlDB.Database.Connection.ConnectionString))
                {
                    sqlConn.Open();
                    SqlDataAdapter sda = new SqlDataAdapter(sbSql.ToString(), sqlConn);

                    sda.Fill(dt);
                }

                return JavaScript(JsonConvert.SerializeObject(dt));
            }

            return Json(KlDB.KnowledgeDetails, JsonRequestBehavior.AllowGet);
        }


        public ActionResult GetDetial2Type(Int32 id) {
            var models = KlDB.Details2Types.Where(m => m.KnowledgeDetails_ID == id);
            return Json(models, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Create(Models.Knowledge.KnowledgeDetail knowledgeDetail)
        {
            Models.AjaxResult ar = new Models.AjaxResult();
            try
            {
                KlDB.KnowledgeDetails.Add(knowledgeDetail);
                KlDB.SaveChanges();

                string userData = this.HttpContext.Request.Form["userData"];
                foreach (var ud in userData.Split(',')) {
                    Models.Knowledge.Details2Type d2t = new Models.Knowledge.Details2Type();
                    d2t.KnowledgeDetails_ID = knowledgeDetail.id;
                    d2t.KnowledgeDetailsType_ID = Int32.Parse(ud);
                    KlDB.Details2Types.Add(d2t);
                }

                KlDB.SaveChanges();

                //Hubs.UserHub.Instance.Clients.All.Create(knowledgeDetail);
            }
            catch (Exception ex) {
                ar.Success = false;
                ar.Data = ex.Message;
            }

            ar.Data = knowledgeDetail.id;
            return Json(ar);
        }

        public ActionResult Update(Int32 id, Models.Knowledge.KnowledgeDetail knowledgeDetail)
        {
            Models.AjaxResult ar = new Models.AjaxResult();
            try
            {
                var deletes = KlDB.Details2Types
                    .Where<Models.Knowledge.Details2Type>(m => m.KnowledgeDetails_ID == id);
                foreach (var delete in deletes)
                {
                    KlDB.Details2Types.Remove(delete);
                }

                var curKnowledgeDetail = KlDB.KnowledgeDetails.Find(id);
                curKnowledgeDetail.Title = knowledgeDetail.Title;
                curKnowledgeDetail.Remarks = knowledgeDetail.Remarks;
                curKnowledgeDetail.Cases = knowledgeDetail.Cases;
                curKnowledgeDetail.DisposeType_ID = knowledgeDetail.DisposeType_ID;

                string userData = this.HttpContext.Request.Form["userData"];
                if (!String.IsNullOrWhiteSpace(userData))
                {
                    foreach (var ud in userData.Split(','))
                    {
                        Models.Knowledge.Details2Type d2t = new Models.Knowledge.Details2Type();
                        d2t.KnowledgeDetails_ID = knowledgeDetail.id;
                        d2t.KnowledgeDetailsType_ID = Int32.Parse(ud);
                        KlDB.Details2Types.Add(d2t);
                    }
                }

                KlDB.SaveChanges();

                //Hubs.UserHub.Instance.Clients.All.Update(curKnowledgeDetail);
            }
            catch (Exception ex)
            {
                ar.Success = false;
                ar.Data = ex.Message;
            }

            return Json(ar);
        }

        public ActionResult Delete(int id) {
            Models.AjaxResult ar = new Models.AjaxResult();
            try
            {
                var deletes = KlDB.Details2Types
                    .Where<Models.Knowledge.Details2Type>(m => m.KnowledgeDetails_ID == id);
                foreach (var delete in deletes)
                {
                    KlDB.Details2Types.Remove(delete);
                }

                var curUser = KlDB.KnowledgeDetails.Find(id);
                KlDB.KnowledgeDetails.Remove(curUser);
                KlDB.SaveChanges();

                //Hubs.UserHub.Instance.Clients.All.Delete(curUser);
            }
            catch (Exception ex)
            {
                ar.Success = false;
                ar.Data = ex.Message;
            }

            return Json(ar);
        }


        private KlDataBase KlDB = new KlDataBase();

    }
}
